package com.udi.project.business.local.di.thread;


import com.udi.common.exception.base.BaseException;
import com.udi.common.utils.spring.SpringUtils;
import com.udi.project.business.local.di.domain.DtDi;
import com.udi.project.business.local.di.mapper.DiGenerateMapper;
import com.udi.project.business.utils.redis.RedisUtils;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Admin
 * 持久化DI子线程
 */
@Component
@Slf4j
@Log(topic = "持久化DI子线程")
public class Endurance extends Thread{



    private DiGenerateMapper diGenerateMapper;
    private RedisUtils redisUtils;

    public Endurance() {
        this.redisUtils = SpringUtils.getBean(RedisUtils.class);
        this.diGenerateMapper = SpringUtils.getBean(DiGenerateMapper.class);
    }

    @SneakyThrows
    @Override
    public void run() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());

        //持久化
       List<Object> redisList = redisUtils.lGet("diCode",0,-1);
       String deptId = (String) redisUtils.get("deptId");
        if(redisList == null){
            Thread.sleep(1000);
            redisList = redisUtils.lGet("diCode",0,-1);
        }
        String type = (String) redisUtils.get("type");
        Integer pkgNum = (Integer) redisUtils.get("pkgNum");
        List<DtDi> diList = new ArrayList<>();
        for(Object i:redisList){
            DtDi dtDi = new DtDi();
            dtDi.setDi(i);
            dtDi.setStatus("0");
            dtDi.setUseInfo("暂无");
            dtDi.setPkgNum(pkgNum.toString());
            dtDi.setType(type);
            dtDi.setAddTime(date);
            dtDi.setDeptId(deptId);
            diList.add(dtDi);
        }
        int ov = diGenerateMapper.insertDi(diList);
        if(redisList.size()==0 || ov==0){
            redisUtils.lSet("ThreadHint","{\"messg\":\"DI持久化失败\",\"TypeNumber\":5001},");
            throw new BaseException("DI持久化失败");
        }else {
            redisUtils.del("type","diCode");
            redisUtils.del("corpid");
            if(redisUtils.hasKey("corpid")){
                redisUtils.del("corpid");
            }
            log.info("DI持久化成功");
        }
    }
}
